package com.example.sanguogameserver.config;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.example.sanguogameserver.annotations.IgnoreResultAdvice;
import com.example.sanguogameserver.response.base.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import java.util.Arrays;

/**
 * 处理解析 {@link ResponseBodyAdvice} 统一返回包装器
 */
@RestControllerAdvice
@RequiredArgsConstructor
public class CommonResponseDataAdvice implements ResponseBodyAdvice<Object> {

    private final ReponseAdviceConfig reponseAdviceConfig;

    @Override
    public boolean supports(MethodParameter methodParameter,
                            Class<? extends HttpMessageConverter<?>> aClass) {
        return filter(methodParameter);
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType,
                                  Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {
        String ignoreUrls = reponseAdviceConfig.getIgnoreUrls();
        if (StrUtil.isNotBlank(ignoreUrls)) {
            AntPathMatcher antPathMatcher = new AntPathMatcher();
            boolean isIgnoreMatch = Arrays.stream(ignoreUrls.split(","))
                    .anyMatch(ignoreUrl -> antPathMatcher.match(ignoreUrl, ((ServletServerHttpRequest) serverHttpRequest).getServletRequest().getRequestURI()));
            if (isIgnoreMatch) return o;
        }
        // o is null -> return response

        if (o == null) {
            return Result.success("成功");
        }
        // o is instanceof ConmmonResponse -> return o
        if (o instanceof Result) {
            return o;
        }
        // string 特殊处理
        if (o instanceof String) {

            return JSON.toJSONString(Result.success("",o.toString()));
        }
        return Result.success("成功", o);
    }

    private Boolean filter(MethodParameter methodParameter) {
        // 判断是否过滤,都需要过滤
        if (methodParameter.getMethodAnnotation(IgnoreResultAdvice.class) != null) {
            return false;
        }
        if (methodParameter.getMethod().getDeclaringClass().getAnnotation(IgnoreResultAdvice.class) != null) {
            return false;
        }
        return true;
    }

}
